package basic.commons.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadUtil {

	public static void downloadPublic(String fullPath,HttpServletResponse response,
			HttpServletRequest request) throws ServletException, IOException {

		// 下载文件
		InputStream is = null;
		OutputStream servletOutputStream = null;
		int len = 0;
		try {
			// 读取服务器文件
			File targetfile = new File(fullPath);
			if (targetfile.exists()) {
				String contentType = "application/octet-stream";
				response.setContentType(contentType);
				// 写明要下载的文件的大小
				response.setContentLength((int) targetfile.length());
				String agent = request.getHeader("USER-AGENT");
				String[] paths = fullPath.split("/");
				if (agent.contains("AppleWebKit")) {
					response.setHeader("Content-Disposition", "attachment;filename=" + paths[paths.length-1]);
				} else {
					response.setHeader("Content-Disposition", "attachment;filename=" + paths[paths.length-1]);
				}
				is = new FileInputStream(targetfile);
				servletOutputStream = response.getOutputStream();
				byte[] buffer = new byte[1024];
				len = 0;
				while ((len = is.read(buffer, 0, 1024)) != -1) {
					servletOutputStream.write(buffer, 0, len);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null)
				is.close();
			if (servletOutputStream != null) {
				servletOutputStream = null;
			}
		}

	}
	

}
